package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.UseMyHomeRecycleViewAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.GoodsSelectBean;
import com.weixin.paleituo.bean.SpecificationListBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.UseMyHomeBean;
import com.weixin.paleituo.bean.UseMyHomeInfo;
import com.weixin.paleituo.bean.UserMyHomeListBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.UseMyHomeAttrEvent;
import com.weixin.paleituo.eventbus.UseMyHomeCheckPosition;
import com.weixin.paleituo.eventbus.UseMyHomeSureEvent;
import com.weixin.paleituo.eventbus.UserMyHomeNumberEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.SelectGoodsAttriUseMyHomePopuWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 应用到我家
 */
public class UseMyHomeActivity extends BasePersonActivity {


    @BindView(R.id.recycle_activity_use_my_home)
    RecyclerView mRecycleActivityUseMyHome;
    @BindView(R.id.view_line_activity_use_my_home)
    View mViewLineActivityUseMyHome;
    @BindView(R.id.cb_all_select_activity_use_my_home)
    CheckBox mCbAllSelectActivityUseMyHome;
    @BindView(R.id.rl_allselect_activity_use_my_home)
    RelativeLayout mRlAllselectActivityUseMyHome;
    @BindView(R.id.tv_money_activity_use_my_home)
    TextView mTvMoneyActivityUseMyHome;
    @BindView(R.id.tv_goaccount_activity_use_my_home)
    TextView mTvGoaccountActivityUseMyHome;
    @BindView(R.id.ll_bottomroot_activity_use_my_home)
    LinearLayout mLlBottomrootActivityUseMyHome;
    private LoadingPagerHead mLoadingPagerHead;
    private int mPrototyperoomid;
    private List<UserMyHomeListBean> mUserMyHomeListBeans=new ArrayList<>();
    private UseMyHomeRecycleViewAdapter mUseMyHomeRecycleViewAdapter;
    private  boolean isAllSelect;
    private SelectGoodsAttriUseMyHomePopuWindow mSelectGoodsAttriUseMyHomePopuWindow;
    private Dialog mLoadingDialog;
    private int mTempId;

    @Override
    protected View getContentView(Context context) {
        mLoadingPagerHead = new LoadingPagerHead(this) {
            @Override
            protected void close() {

            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(UseMyHomeActivity.this, R.layout.activity_use_my_home);
            }

            @Override
            protected void reLoading() {
                retry();

            }
        };
       // setContentView(R.layout.activity_use_my_home);
        return mLoadingPagerHead;
    }

    /**
     * 重新加载
     */
    private void retry() {

        Observable<StatusCode<List<UserMyHomeListBean>>> statusCodeObservable = ApiUtils.getApi().userMyhouseList(BaseApplication.sUserInfoBean.getUserId(), mPrototyperoomid, Contans.defaultToken);

        HttpUtil.getInstance().toSubscribe(statusCodeObservable, new ProgressSubscriber<List<UserMyHomeListBean>>(this) {
            @Override
            protected void _onNext(StatusCode<List<UserMyHomeListBean>> listStatusCode) {

                List<UserMyHomeListBean> userMyHomeListBeans = listStatusCode.getData();
                if (userMyHomeListBeans != null && userMyHomeListBeans.size() > 0) {
                    mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                    mUserMyHomeListBeans.clear();
                    mUserMyHomeListBeans.addAll(userMyHomeListBeans);
                    mUseMyHomeRecycleViewAdapter.notifyDataSetChanged();
                    setSelectAllState();
                    mTvGoaccountActivityUseMyHome.setText(calulateSelecteNumber()==0?"去结算":"去结算("+calulateSelecteNumber()+")");
                } else {
                    mLoadingPagerHead.showPagerView(Contans.STATE_EMPTY);
                    LogUtils.i(TAG, listStatusCode.getDetailMsg());
                }
            }

            @Override
            protected void _onError(String message) {
                mLoadingPagerHead.showPagerView(Contans.STATE_ERROR);
                LogUtils.i(TAG, message);

            }
        }, "", lifecycleSubject, false, true);


    }

    @Override
    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        mPrototyperoomid = intent.getIntExtra(Contans.INTENT_DATA, 0);
        mTempId = intent.getIntExtra(Contans.INTENT_TYPE,0);
        mTvTitle.setVisibility(View.VISIBLE);
        mTvTitle.setText("应用到我家");
        mUserMyHomeListBeans.clear();
        mUseMyHomeRecycleViewAdapter = new UseMyHomeRecycleViewAdapter(this,mUserMyHomeListBeans);
        mRecycleActivityUseMyHome.setLayoutManager(new LinearLayoutManager(this));
        mRecycleActivityUseMyHome.setItemAnimator(new DefaultItemAnimator());
        mRecycleActivityUseMyHome.setAdapter(mUseMyHomeRecycleViewAdapter);
       // mTvMoneyActivityUseMyHome.setText("￥" + UIUtils.getMoney(calueSumPrice()));
        setShowSumPrice();

        retry();
    }

    /**
     * 设置总价的显示
     */

    private void setShowSumPrice(){

        double sumPrice = calueSumPrice();
        if (sumPrice>0){
            mTvMoneyActivityUseMyHome.setText("￥" + UIUtils.getMoney(calueSumPrice()));

        }else {
            boolean isAwaitPrice=false;


            for (UserMyHomeListBean userMyHomeListBean:mUserMyHomeListBeans){

                if (userMyHomeListBean.isCheck() && userMyHomeListBean.isAlreadyCustom()){

                    isAwaitPrice=true;
                    break;

                }

            }
            if (isAwaitPrice){
                mTvMoneyActivityUseMyHome.setText( "￥待定");
            }else {
                mTvMoneyActivityUseMyHome.setText("￥" + UIUtils.getMoney(calueSumPrice()));
            }

        }



    }


    /**
     * @param context
     * @param prototyperoomid 样板间Id
     */
    public static void startActivity(Context context, int prototyperoomid, int tempId) {
        Intent intent = new Intent(context, UseMyHomeActivity.class);
        intent.putExtra(Contans.INTENT_DATA, prototyperoomid);
        intent.putExtra(Contans.INTENT_TYPE, tempId);
        context.startActivity(intent);

    }


    @OnClick(R.id.rl_allselect_activity_use_my_home)
    public void onMRlAllselectActivityUseMyHomeClicked() {
        if (isAllSelect){
            isAllSelect=false;
            mCbAllSelectActivityUseMyHome.setBackgroundResource(R.mipmap.xe_h);

            setIsAllSelect(false);

        }else {
            isAllSelect=true;
            mCbAllSelectActivityUseMyHome.setBackgroundResource(R.mipmap.chooce_green);
            setIsAllSelect(true);
        }
        mUseMyHomeRecycleViewAdapter.notifyDataSetChanged();
        mTvGoaccountActivityUseMyHome.setText(calulateSelecteNumber()==0?"去结算":"去结算("+calulateSelecteNumber()+")");
      //  mTvMoneyActivityUseMyHome.setText("￥" + UIUtils.getMoney(calueSumPrice()));
        setShowSumPrice();

    }

    @OnClick(R.id.tv_goaccount_activity_use_my_home)
    public void onMTvGoaccountActivityUseMyHomeClicked() {


        if (BaseApplication.isLoginSuccess){
            //去结算
            int i = calulateSelecteNumber();

            if (i==0){
                ToastUtils.makeText("你还没有选择商品哦");
                return;
            }
            UseMyHomeBean useMyHomeBean=new UseMyHomeBean();

            useMyHomeBean.setToken(BaseApplication.sUserInfoBean.getToken());
            useMyHomeBean.setUserId(BaseApplication.getUserId());
            useMyHomeBean.setPrototyperoomid((long)mTempId);
/*"goodsId":912,#商品idL
			"storeId":91,#店铺id
			"goodsSpecsInfo":"...",#商品属性
			"idlist":"12_56_",#属性id
			"madeType":"2",#定制类型1为定制 2为非定制
			"msg":"",#定制信息
            "goodsSalenum": 1#商品数量
*/
            List<UseMyHomeInfo> useMyHomeInfos=new ArrayList<>();
            useMyHomeInfos.clear();

            for (UserMyHomeListBean userMyHomeListBean:mUserMyHomeListBeans) {
                if (userMyHomeListBean.isCheck()){
                    UseMyHomeInfo useMyHomeInfo=new UseMyHomeInfo();
                    //  useMyHomeInfo.set
                    useMyHomeInfo.setGoodsId(userMyHomeListBean.getId());
                    useMyHomeInfo.setStoreId(userMyHomeListBean.getStoreId());
                    useMyHomeInfo.setGoodsSpecsInfo(userMyHomeListBean.getSpecinfo());
                    List<SpecificationListBean> specificationList = userMyHomeListBean.getSpecificationList();
                    String idList="";
                    if (specificationList!=null&&specificationList.size()>0){

                        for ( SpecificationListBean specificationList1:specificationList){

                            int checkId = specificationList1.getCheckId();
                            idList=idList+checkId+"_";
                        }
                    }

                    useMyHomeInfo.setIdlist(idList.trim());

                    useMyHomeInfo.setMadeType(userMyHomeListBean.isAlreadyCustom()?"1":"2");
                    useMyHomeInfo.setMsg(userMyHomeListBean.getCustomInfo());
                    useMyHomeInfo.setGoodsSalenum(userMyHomeListBean.getNum());
                    useMyHomeInfos.add(useMyHomeInfo);

                }

            }
            useMyHomeBean.setCartlist(useMyHomeInfos);


            Observable statusCodeObservable = ApiUtils.getApi().submintUseMyHome(useMyHomeBean)
                    .compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            if (mLoadingDialog == null) {
                                mLoadingDialog = LoadingDialogUtils.createLoadingDialog(UseMyHomeActivity.this, "");
                            }
                            LoadingDialogUtils.show(mLoadingDialog);
                        }
                    }).subscribeOn(AndroidSchedulers.mainThread());
            HttpUtil.getInstance().toSubscribe(statusCodeObservable, new ProgressSubscriber<String>(UseMyHomeActivity.this) {
                @Override
                protected void _onNext(StatusCode statusCode) {
                    LoadingDialogUtils.closeDialog(mLoadingDialog);

                    Intent intent = CreateSharedOrderActivity.call2CreateSharedOrder(UseMyHomeActivity.this,mTempId);
                    startActivity(intent);
                    finish();


                }

                @Override
                protected void _onError(String message) {
                    LoadingDialogUtils.closeDialog(mLoadingDialog);
                    ToastUtils.makeText("添加失败");

                }


            },"",lifecycleSubject,false,true);


        }else {

            LoginActivity.startActivity(this,true);

        }




       // submintUseMyHome





    }

    /**
     * 修改数量
     * @param userMyHomeNumberEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBusEvent(UserMyHomeNumberEvent userMyHomeNumberEvent){
        int number = userMyHomeNumberEvent.getNumber();
        int useMyHomeposition = userMyHomeNumberEvent.getUseMyHomeposition();

        if (number>0){

            mUserMyHomeListBeans.get(useMyHomeposition).setNum(number);
        }
        mTvGoaccountActivityUseMyHome.setText(calulateSelecteNumber()==0?"去结算":"去结算("+calulateSelecteNumber()+")");
     //   mTvMoneyActivityUseMyHome.setText("￥" + UIUtils.getMoney(calueSumPrice()));
        setShowSumPrice();

    }

    /**
     * 选中位置
     * @param useMyHomeCheckPosition
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void useMyHomeCheckPosition(UseMyHomeCheckPosition useMyHomeCheckPosition){
        int useMyHomechekPosition = useMyHomeCheckPosition.getUseMyHomechekPosition();
        boolean chek = useMyHomeCheckPosition.isChek();
        mUserMyHomeListBeans.get(useMyHomechekPosition).setCheck(chek);
        mUseMyHomeRecycleViewAdapter.notifyDataSetChanged();
        setSelectAllState();


        mTvGoaccountActivityUseMyHome.setText(calulateSelecteNumber()==0?"去结算":"去结算("+calulateSelecteNumber()+")");
      //  mTvMoneyActivityUseMyHome.setText("￥" + UIUtils.getMoney(calueSumPrice()));
        setShowSumPrice();


    }

    /**
     * 弹窗
     */
    private GoodsSelectBean mGoodsSelectBean;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void useMyHomeAttrEvent(UseMyHomeAttrEvent useMyHomeAttrEvent){
            int postion = useMyHomeAttrEvent.getPostion();
        UserMyHomeListBean userMyHomeListBean = mUserMyHomeListBeans.get(postion);
        mSelectGoodsAttriUseMyHomePopuWindow = new SelectGoodsAttriUseMyHomePopuWindow(this,lifecycleSubject);

        mSelectGoodsAttriUseMyHomePopuWindow.setCustomized(userMyHomeListBean.getCustomized());
        mGoodsSelectBean =new GoodsSelectBean();
        mGoodsSelectBean.setStorePrice(Double.valueOf(userMyHomeListBean.getPrice()));
        mGoodsSelectBean.setSelectedLastName(userMyHomeListBean.getSpecinfo());
        mGoodsSelectBean.setSelectNumber(userMyHomeListBean.getNum());
        mGoodsSelectBean.setSummary(userMyHomeListBean.getListUrl());
        mGoodsSelectBean.setCustomMessage(userMyHomeListBean.getCustomInfo());
        String coupon = userMyHomeListBean.getCoupon()+"";


        if (!StringUtils.isEmpty(coupon)){
            mGoodsSelectBean.setCoupon(Double.valueOf(userMyHomeListBean.getCoupon()));
        }
        mGoodsSelectBean.setGoodsName(userMyHomeListBean.getGoodsName());
        mGoodsSelectBean.setGoodsId(userMyHomeListBean.getId()+"");
        mGoodsSelectBean.setStoreId(userMyHomeListBean.getStoreId()+"");
        String specialSales = userMyHomeListBean.getSpecialSales();
        if (!StringUtils.isEmpty(specialSales)){
            mGoodsSelectBean.setVip(true);
            mGoodsSelectBean.setVipPrice(Double.valueOf(specialSales));
        }else {
            mGoodsSelectBean.setVip(false);
        }


        mSelectGoodsAttriUseMyHomePopuWindow.setGoodsSelectBean(mGoodsSelectBean,userMyHomeListBean.getId());
        List<SpecificationListBean> specificationList = userMyHomeListBean.getSpecificationList();
        if (specificationList!=null &&specificationList.size()>0){

            mSelectGoodsAttriUseMyHomePopuWindow.setList(specificationList);

        }
        mSelectGoodsAttriUseMyHomePopuWindow.setPosition(postion);

        mSelectGoodsAttriUseMyHomePopuWindow.refresh();
        mSelectGoodsAttriUseMyHomePopuWindow.showAtLocation(mRecycleActivityUseMyHome, Gravity.CENTER, 0, 0);



}

    /**
     * 确定
     * @param useMyHomeSureEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void useMyHomeSureEvent(UseMyHomeSureEvent useMyHomeSureEvent){

        int postion = useMyHomeSureEvent.getPostion();
        UserMyHomeListBean userMyHomeListBean = mUserMyHomeListBeans.get(postion);
        String iconUrl = useMyHomeSureEvent.getIconUrl();
        String lastName = useMyHomeSureEvent.getLastName();
        int number = useMyHomeSureEvent.getNumber();
        int[] selectIdArr = useMyHomeSureEvent.getSelectIdArr();
        boolean alreadyCustom = useMyHomeSureEvent.isAlreadyCustom();
        String customInfo = useMyHomeSureEvent.getCustomInfo();
        String price = useMyHomeSureEvent.getPrice();
        String specialSales = useMyHomeSureEvent.getSpecialSales();


        userMyHomeListBean.setCustomInfo(customInfo);

        userMyHomeListBean.setAlreadyCustom(alreadyCustom);
        userMyHomeListBean.setNum(number);

        userMyHomeListBean.setListUrl(iconUrl);
        userMyHomeListBean.setSpecinfo(lastName);
        userMyHomeListBean.setPrice(price);
        userMyHomeListBean.setSpecialSales(specialSales);

        List<SpecificationListBean> specificationList = userMyHomeListBean.getSpecificationList();
        if (specificationList!=null & specificationList.size()>0 &&selectIdArr!=null &&selectIdArr.length>0){
            for (int j=0;j<specificationList.size();j++){
                specificationList.get(j).setCheckId(selectIdArr[j]);
            }

        }

        mUseMyHomeRecycleViewAdapter.notifyDataSetChanged();
       // mTvMoneyActivityUseMyHome.setText("￥" + UIUtils.getMoney(calueSumPrice()));
        setShowSumPrice();


    }

    /**
     * 点击全选
     * @param isAllSelect
     */
    public void setIsAllSelect(boolean isAllSelect){

        for (UserMyHomeListBean userMyHomeListBean:mUserMyHomeListBeans) {

            userMyHomeListBean.setCheck(isAllSelect);
        }

    }


    /**
     * 设置全选
     */
    private void setSelectAllState() {
        for (UserMyHomeListBean userMyHomeListBean:mUserMyHomeListBeans) {

            if (!userMyHomeListBean.isCheck()) {
                isAllSelect = false;
                break;
            } else {
                isAllSelect = true;

            }
        }

        if (isAllSelect) {
            mCbAllSelectActivityUseMyHome.setBackgroundResource(R.mipmap.chooce_green);
        } else {
            mCbAllSelectActivityUseMyHome.setBackgroundResource(R.mipmap.xe_h);

        }
    }
    /**
     * 计算选中的数量
     *
     * @return
     */
    private int calulateSelecteNumber() {
        int selectNumber = 0;
        for (UserMyHomeListBean userMyHomeListBean:mUserMyHomeListBeans) {
       if (userMyHomeListBean.isCheck()){
           selectNumber+=userMyHomeListBean.getNum();

       }
        }
        return selectNumber;
    }

    /**
     * 总计
     * @return
     */
    private double calueSumPrice(){
        double price=0;
        for (UserMyHomeListBean userMyHomeListBean:mUserMyHomeListBeans) {
            if (userMyHomeListBean.isCheck() &&!userMyHomeListBean.isAlreadyCustom()) {
                String specialSales = userMyHomeListBean.getSpecialSales();
                if (StringUtils.isEmpty(specialSales)){
                    //
                    price+=userMyHomeListBean.getNum()*Double.valueOf(userMyHomeListBean.getPrice());
                }else {
                    price+=userMyHomeListBean.getNum()*Double.valueOf(userMyHomeListBean.getSpecialSales());
                }
            }
        }
        return price;
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
